import {Component, OnInit} from '@angular/core';
import {HttpErrorResponse} from '@angular/common/http';
import {AuthService} from '../../_services/auth.service';
import {Router} from '@angular/router';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {MsgResponse} from '../../_models/response';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
})
export class LoginComponent implements OnInit {
  loginType: boolean;
  validateForm: FormGroup;

  constructor(private authService: AuthService, private router: Router, private fb: FormBuilder) {
    this.loginType = true;
  }


  ngOnInit() {
    this.validateForm = this.fb.group({
      userName: [null, [Validators.required]],
      password: [null, [Validators.required]]
      //  remember: [true],
    });
  }

  _submitForm() {
    for (const i in this.validateForm.controls) {
      if (this.validateForm.controls.hasOwnProperty(i)) {
        this.validateForm.controls[i].markAsDirty();
      }
    }
    this._login();
  }

  _login(): void {
    console.log(this.validateForm.value);
    this.authService.doLogin(this.validateForm.value).subscribe(
      (data: MsgResponse) => {
        console.log(data);
        if (data.StatusOk) {
          this.authService.jwtToken = data.Msg;
        } else {
          console.log(data.Msg);
        }
      },
      (err: HttpErrorResponse) => {
        console.log(err.error);
      }
    );
  }

}
